package com.fanfanwang.ffw.app.ui.home;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviPara;
import com.fanfanwang.ffw.app.AppConstant;
import com.fanfanwang.ffw.app.AppManager;
import com.fanfanwang.ffw.app.R;
import com.fanfanwang.ffw.app.asynctask.GetParkingInfoAsyncTask;
import com.fanfanwang.ffw.app.asynctask.OrderDoneAsyncTask;
import com.fanfanwang.ffw.app.bean.ParkingInfoBean;
import com.fanfanwang.ffw.app.bean.YuyueInfoBean;
import com.fanfanwang.ffw.app.common.ToastAlone;
import com.fanfanwang.ffw.app.receiver.OneShotAlarm;
import com.fanfanwang.ffw.app.tools.SharedPreferencesUtil;
import com.fanfanwang.ffw.app.tools.TimeUtils;
import com.fanfanwang.ffw.app.ui.login.LoginAct;
import com.fanfanwang.ffw.app.widget.CommonTitleBar;

/** 路段详情 */
public class SectionDetailAct extends com.fanfanwang.ffw.app.base.BaseActivity {

	private CommonTitleBar commonTitleBar;
	private Activity mAct;
	private Intent mIntent;
	private TextView section_distance, section_place, set_null_carport,
	set_sum_carport, set_charging_stand, set_charging_time,
	set_parking_type, set_start_time, set_end_time, section_look_line,
	tv_start_navigation;
	private Button btn_yuyue;
	private ImageView iv_navigation;
	Calendar rightNow;
	private ImageView iv_route;
	private TextView btn_look_line;
	public static IGetParkingInfoable iGetParkingInfoable;
	private String parkingid;
	private String longitude1;
	private String latitude1;
	private String starttime;
	private String address;
	private LocationClient locClient;// 定位对象
	private RelativeLayout rl_line;
	private RelativeLayout rl_nav;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initWidget();
		AppManager.getAppManager().addActivity(this);
		getLocation();
		initData();
		setListener();
	}

	/**
	 * 定位获取当前经纬度
	 */
	public void getLocation() {
		// 实例化位置客户端19
		locClient = new LocationClient(getApplicationContext());
		// 创建一个位置option对象21
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		// option.setScanSpan(5000);
		option.setIsNeedAddress(true); // 返回的信息包含当前的地址26
		// 将封装的参数设置到位置客户端32
		locClient.setLocOption(option);
		locClient.start();
		locClient.registerLocationListener(new BDLocationListener() {

			@Override
			public void onReceiveLocation(BDLocation loc) {
				// TODO Auto-generated method stub
				AppConstant.NOWLATITUDE = loc.getLatitude();
				AppConstant.NOWLONGITUDE = loc.getLongitude();
				AppConstant.NOWADDRESS = loc.getAddrStr();
			}
		});
	}

	public void initWidget() {
		setContentView(R.layout.activity_section_detail);
		mAct = this;
		commonTitleBar = (CommonTitleBar) findViewById(R.id.common_titlebar);
		rightNow = Calendar.getInstance();
		section_distance = (TextView) findViewById(R.id.section_distance);
		section_place = (TextView) findViewById(R.id.section_place);
		set_null_carport = (TextView) findViewById(R.id.set_null_carport);
		set_sum_carport = (TextView) findViewById(R.id.set_sum_carport);
		set_charging_stand = (TextView) findViewById(R.id.set_charging_stand);
		set_charging_time = (TextView) findViewById(R.id.set_charging_time);
		set_parking_type = (TextView) findViewById(R.id.set_parking_type);
		set_start_time = (TextView) findViewById(R.id.set_start_time);
		set_end_time = (TextView) findViewById(R.id.set_end_time);
		section_look_line = (TextView) findViewById(R.id.section_look_line);
		tv_start_navigation = (TextView) findViewById(R.id.tv_start_navigation);
		btn_yuyue = (Button) findViewById(R.id.btn_yuyue);
		iv_navigation = (ImageView) findViewById(R.id.iv_navigation);
		iv_route = (ImageView) findViewById(R.id.iv_route);
		btn_look_line = (TextView) findViewById(R.id.section_look_line);
		rl_line = (RelativeLayout) findViewById(R.id.rl_line);
		rl_nav = (RelativeLayout) findViewById(R.id.rl_nav);
	}

	@Override
	public void initData() {
		commonTitleBar.setCenterText(getString(R.string.section_desc));
		commonTitleBar.setReturnVisible();
		Intent intent = getIntent();
		longitude1 = intent.getStringExtra("longitude1");
		latitude1 = intent.getStringExtra("latitude1");
		parkingid = intent.getStringExtra("id");
		if (!TextUtils.isEmpty(parkingid)) {
			new GetParkingInfoAsyncTask(mAct, parkingid,
					AppConstant.NOWLONGITUDE + "", AppConstant.NOWLATITUDE + "")
			.execute("");
		}
		// 调用一下接口
		setInterface();
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub

	}

	public void startRouteLine() {
		String startAddress;
		if (!TextUtils.isEmpty(AppConstant.NOWADDRESS)) {
			startAddress = AppConstant.NOWADDRESS;
		} else {
			startAddress = SharedPreferencesUtil.getInstance(mAct)
					.getNowAddress();
		}
		Intent intent = new Intent();
		intent.setClass(mAct, RoutePlanDemo.class);
		intent.putExtra("startAddress", startAddress);
		intent.putExtra("endAddress", address);
		if (!TextUtils.isEmpty(startAddress) && !TextUtils.isEmpty(address)) {
			startActivity(intent);
		}

	}

	/**
	 * @param view导航功能
	 *            。
	 */
	public void startWebNavi(View view) {
				LatLng pt1 = new LatLng(AppConstant.NOWLATITUDE,
						AppConstant.NOWLONGITUDE);
				LatLng pt2 = new LatLng(Double.parseDouble(latitude1.trim()),
						Double.parseDouble(longitude1.trim()));
//		LatLng pt1 = new LatLng(38.032581, 114.553208);
//		LatLng pt2 = new LatLng(38.042258, 114.486270);
		// 构建 导航参数
		try {
			NaviPara para = new NaviPara();
			para.startPoint = pt1;
			para.startName = "从这里开始";
			para.endPoint = pt2;
			para.endName = "到这里结束";
			BaiduMapNavigation.openBaiduMapNavi(para, SectionDetailAct.this);
		} catch (BaiduMapAppNotSupportNaviException e) {
			NaviPara para = new NaviPara();
			para.startPoint = pt1;
			para.endPoint = pt2;
			BaiduMapNavigation.openWebBaiduMapNavi(para, SectionDetailAct.this);
		}

	}

	@Override
	protected void setListener() {

		rl_nav.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				startWebNavi(v);
			}
		});
		commonTitleBar.setToolBarReturnOnclickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		set_start_time.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				int hourOfDay = rightNow.get(Calendar.HOUR_OF_DAY);
				int minute = rightNow.get(Calendar.MINUTE);
				new TimePickerDialog(mAct, new OnTimeSetListener() {

					@Override
					public void onTimeSet(TimePicker view, int hourOfDay,
							int minute) {
						// TODO Auto-generated method stub
						set_start_time.setText(hourOfDay + ":" + minute);
					}
				}, hourOfDay, minute, true).show();
			}
		});
		set_end_time.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				int hourOfDay = rightNow.get(Calendar.HOUR_OF_DAY);
				int minute = rightNow.get(Calendar.MINUTE);
				new TimePickerDialog(mAct, new OnTimeSetListener() {

					@Override
					public void onTimeSet(TimePicker view, int hourOfDay,
							int minute) {
						set_end_time.setText(hourOfDay + ":" + minute);
					}
				}, hourOfDay, minute, true).show();
			}
		});
		btn_yuyue.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				starttime = set_start_time.getText().toString();
				String endtime = set_end_time.getText().toString();
				if (getString(R.string.click_set).equals(starttime)) {
					ToastAlone.showToast(mAct,
							getString(R.string.click_set_starttime)).show();
				} else if (getString(R.string.click_set).equals(endtime)) {
					ToastAlone.showToast(mAct,
							getString(R.string.click_set_endtime)).show();
				} else if (com.fanfanwang.ffw.app.tools.TimeUtils.compareTime(
						starttime, endtime)) {
					ToastAlone.showToast(mAct, getString(R.string.time_error),
							Toast.LENGTH_SHORT).show();

				} else {
					Calendar c = Calendar.getInstance();// 可以对每个时间域单独修改

					int year = c.get(Calendar.YEAR);
					int month = (c.get(Calendar.MONTH) + 1);
					int date = c.get(Calendar.DATE);
					starttime = year + "-" + month + "-" + date + " "
							+ starttime;
					endtime = year + "-" + month + "-" + date + " " + endtime;
					if (SharedPreferencesUtil.getInstance(mAct).getUserId() != null) {
						new OrderDoneAsyncTask(mAct, SharedPreferencesUtil
								.getInstance(mAct).getUserId(), parkingid,
								starttime, endtime).execute("");
					} else {
						ToastAlone.showToast(mAct, "未登录无法预约，请登录");
						Intent intent = new Intent(mAct, LoginAct.class);
						startActivity(intent);
					}
				}

			}
		});
		rl_line.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startRouteLine();

			}
		});
	}

	public interface IGetParkingInfoable {
		public void setParkingInfo(ParkingInfoBean parkingInfoBean);

		public void setOrderSuccess();
	}

	public void setInterface() {
		iGetParkingInfoable = new IGetParkingInfoable() {

			@Override
			public void setParkingInfo(ParkingInfoBean parkingInfoBean) {
				// 更新ui
				if (parkingInfoBean != null) {
					parkingid = parkingInfoBean.parkingid;
					section_place.setText(AppConstant
							.URLDecoderString(parkingInfoBean.name));
					section_distance.setText(parkingInfoBean.juli + "km");
					set_null_carport.setText(parkingInfoBean.count);
					set_sum_carport.setText(parkingInfoBean.countnums);
					StringBuffer sb = new StringBuffer();
					String chargePrice = parkingInfoBean.chargeprice;
					if (!TextUtils.isEmpty(chargePrice)) {
						sb.append(chargePrice + "元");
					}
					String chargetype = parkingInfoBean.chargetype;
					if (!TextUtils.isEmpty(chargetype)) {
						if (chargetype.equals("0")) {
							sb.append("/次");
						} else {
							sb.append("/时");
						}
					}
					set_charging_stand.setText(sb.toString());
					set_charging_time.setText(AppConstant
							.URLDecoderString(parkingInfoBean.opentime));
					set_parking_type.setText(AppConstant
							.URLDecoderString(parkingInfoBean.parktype));
					address = AppConstant
							.URLDecoderString(parkingInfoBean.address);
				}

			}

			@Override
			public void setOrderSuccess() {
				// TODO Auto-generated method stub
				finish();
				// 预约成功之后，判断如果当前是需要提醒的那就发一个提醒。
				boolean preIsAlarmClock = SharedPreferencesUtil.getInstance(
						mAct).getIsreceivealarmclock();
				if (preIsAlarmClock)// 代表是需要提醒的。
				{
					
					String remindtime = SharedPreferencesUtil.getInstance(
							SectionDetailAct.this).getRemindtime();
					int aheadtime = 20;
					if (remindtime.contains("15")) {
						aheadtime = 15;
					} else if (remindtime.contains("10")) {
						aheadtime = 10;
					}
					
					if (TimeUtils.CompareCurrGTOther2(starttime, "", aheadtime)) {
						Intent intent = new Intent(mAct,
								OneShotAlarm.class);
						PendingIntent sender = PendingIntent.getBroadcast(
								mAct, 0, intent, 0);
						AlarmManager am = (AlarmManager)mAct.getSystemService(Context.ALARM_SERVICE);
						am.set(AlarmManager.RTC_WAKEUP,
								TimeUtils.parseDateToMilliAheadSecond2(starttime,aheadtime),
								sender);
					}
				}
			}
		};
	}

}
